import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.SwingUtilities;

public class Controller {
	
	View theView;
	boolean verbose;
	ArrayBlockingQueue<Point> latestPoint;
	AtomicBoolean continueWork;

	public Controller(View theView, Properties prop, ArrayBlockingQueue<Point> latestPoint, AtomicBoolean continueWork) {
		this.theView = theView;
		verbose = prop.getProperty("verbose").equals("true");		
		this.latestPoint = latestPoint;
		this.continueWork = continueWork;
		
		theView.addKeyListener(new EcsKeyListener());
		theView.addWindowListener(new WindowCloseListener());
	}
	
	public void replaceBox(final int x, final int y, final BufferedImage newImage) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				theView.replaceBox(x, y, newImage);
				theView.repaint();
			}
		});
	}
	
	public void getMouseLocation() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try{
				latestPoint.offer(theView.getContentPane().getMousePosition());
				}
				catch(NullPointerException e){}
			}
		});
	}

	class EcsKeyListener extends KeyAdapter {
       	
		public void keyTyped(KeyEvent arg0) {
       		if((int)arg0.getKeyChar() == 27){
       			theView.dispose();
       			if(verbose) System.out.println("Controller is Exiting...");
       			continueWork.set(false);       			
       		}
		}
    }
	
    class WindowCloseListener extends WindowAdapter {       	
		public void windowClosing(WindowEvent e) {
			theView.dispose();
   			if(verbose) System.out.println("Exiting...");
   			continueWork.set(false);  
		}
    }
  

}
